import { Dropdown, DropdownItem } from "@/ui/Dropdown/Dropdown";
import cls from "@/styles/components/CreateUser/RoleSelector.module.scss";
import React, { useEffect, useState } from "react";
import { Icon } from "@/ui/Icons/Icon";
import cn from "classnames";
import { OptionI } from "@/models/common";
import { UserI } from "@/models/user";

type Props = {
  user: Partial<UserI>;
  updateUser: (v: Partial<UserI>) => void;
  disabled?: boolean;
};

const options = [
  { id: "1.00", name: "1" },
  { id: "0.75", name: "0.75" },
  { id: "0.50", name: "0.5" },
  { id: "0.25", name: "0.25" },
  { id: "0.10", name: "0.1" },
];

export const EmploymentFractionSelector = ({
  user,
  updateUser,
  disabled,
}: Props) => {
  const [roleDropdownOpen, setRoleDropdownOpen] = useState(false);
  const [selected, setSelected] = useState<OptionI>();
  const [isInitialsSet, setIsInitialsSet] = useState(false);

  useEffect(() => {
    if (isInitialsSet) return;
    if (!user.employment_fraction) {
      setIsInitialsSet(true);
      return;
    }
    setSelected(options.find((i) => i.id === user.employment_fraction));
    setIsInitialsSet(true);
  }, [user]);

  useEffect(() => {
    if (isInitialsSet && !selected) setSelected(options[0]);
  }, [isInitialsSet]);

  useEffect(() => {
    if (!selected) return;
    updateUser({
      employment_fraction: String(selected.id),
    });
  }, [selected]);

  const toggleOpen = () => {
    if (disabled) return;
    setRoleDropdownOpen(!roleDropdownOpen);
  };

  return (
    <div className={cls.root}>
      <div className={cls.label}>Ставка</div>
      <div
        className={cn(cls.valueBox, { [cls.disabled]: disabled })}
        onClick={() => toggleOpen()}
      >
        <div className={cls.value}>{selected?.name}</div>
        <button
          type="button"
          onClick={() => toggleOpen()}
          className={cls.arrow}
        >
          <Icon name="arrow" />
        </button>
      </div>
      <Dropdown
        isOpen={roleDropdownOpen}
        close={() => setRoleDropdownOpen(false)}
        parentCls={cls.root}
        fullWidth
      >
        {options?.map((o) => {
          return (
            <DropdownItem key={o.id}>
              <button
                type="button"
                className={cn(cls.option, {
                  [cls.selected]: o.id === selected?.id,
                })}
                onClick={() => {
                  setSelected(o);
                  setRoleDropdownOpen(false);
                }}
              >
                {o.name}
              </button>
            </DropdownItem>
          );
        })}
      </Dropdown>
    </div>
  );
};
